<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item prop="batch">
        <el-input
          v-model="queryParams.batch"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="是否入账" filterable collapse-tags clearable>
          <el-option label="否" value="1"></el-option>
          <el-option label="是" value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="daoruManageId">
        <el-select v-model="queryParams.daoruManageId"
                   filterable reserve-keyword
                   collapse-tags
                   placeholder="导入人"
                   clearable
                   style="width: 240px">
          <el-option v-for="item in sysUserList"
                     :key="item.userId"
                     :label="item.nickName"
                     :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item prop="ruzhangManageId">
        <el-select v-model="queryParams.ruzhangManageId"
                   filterable reserve-keyword
                   collapse-tags
                   placeholder="入账人"
                   clearable
                   style="width: 240px">
          <el-option
            v-for="item in sysUserList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contrastList" @selection-change="handleSelectionChange">
      <el-table-column label="批次号" align="center" prop="batch"/>
      <el-table-column label="导入人" align="center" prop="daoRuNickName"/>
      <el-table-column label="导入时间" align="center" prop="time">
        <template #default="{row}">
          {{ formatTimeTitle(row.time) }}
        </template>
      </el-table-column>
      <el-table-column label="对比订单数量" align="center" prop="count"/>
      <el-table-column label="是否入账" align="center" prop="status">
        <template #default="{row}">
          {{ row.status == 2 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="入账账期" align="center" prop="ruzhangTime"/>
      <el-table-column label="入账人" align="center" prop="ruZhangNickName"/>
      <el-table-column label="入账时间" align="center" prop="ruzhangTime">
        <template #default="{row}">
          {{ row.ruzhangTime ? formatTimeTitle(row.ruzhangTime) : '--' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="toDetail(scope.row)"
          >明细
          </el-button>
          <el-button v-if="scope.row.status == 1"
                     size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['hmk:contrast:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改佣金对比批次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="对比批次:当前时间+随机5位数" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入对比批次:当前时间+随机5位数"/>
        </el-form-item>
        <el-form-item label="对比订单数量" prop="count">
          <el-input v-model="form.count" placeholder="请输入对比订单数量"/>
        </el-form-item>
        <el-form-item label="操作入账的时间" prop="ruzhangTime">
          <el-input v-model="form.ruzhangTime" placeholder="请输入操作入账的时间"/>
        </el-form-item>
        <el-form-item label="对比时间" prop="time">
          <el-input v-model="form.time" placeholder="请输入对比时间"/>
        </el-form-item>
        <el-form-item label="导入人" prop="daoruManageId">
          <el-input v-model="form.daoruManageId" placeholder="请输入导入人"/>
        </el-form-item>
        <el-form-item label="入账人" prop="ruzhangManageId">
          <el-input v-model="form.ruzhangManageId" placeholder="请输入入账人"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      :close-on-click-modal="!upload.isUploading"
      :show-close="!upload.isUploading"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          :disabled="upload.isUploading">
          {{ upload.isUploading ? '上传中...' : '确 定' }}
        </el-button>
        <el-button @click="upload.open = false" :disabled="upload.isUploading">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="contractDetail" width="64%" append-to-body>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
        </div>
        <el-table v-loading="loading" :data="contrastData">
          <el-table-column label="批次号" align="center" prop="batch" width="200px"/>
          <el-table-column label="比对总数量" align="center" prop="count"/>
          <el-table-column label="是否入账" align="center" prop="status">
            <template #default="{row}">
              {{ row.status == 1 ? '否' : '是' }}
            </template>

          </el-table-column>
          <el-table-column label="导入人" align="center" prop="daoRuNickName"/>
          <el-table-column label="入账人" align="center" prop="ruZhangNickName"/>
          <el-table-column label="入账时间" align="center" prop="ruzhangTime">
            <template #default="{row}">
              {{ row.ruzhangTime ? formatTimeTitle(row.ruzhangTime) : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="比对时间" align="center" prop="time">
            <template #default="{row}">
              {{ formatTimeTitle(row.time) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <div style="margin-bottom: 50px"></div>
      <el-card class="box-card" title="卡片">
        <div slot="header" class="clearfix">
          <span>比对信息</span>
        </div>
        <el-table v-loading="loading" :data="contrastDetailList">
          <el-table-column label="商户名称" align="center" prop="businessName"/>
          <el-table-column label="户数" align="center" prop="orderCount"/>
          <el-table-column label="分佣总金额" align="center" prop="sumPrice"/>
        </el-table>
      </el-card>

      <div style="display:flex; justify-content: center; margin-top: 50px">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出数据
        </el-button>
        <el-button
          v-if="showRuZhangButton"
          type="primary"
          plain
          icon="el-icon-coordinate"
          size="mini"
          @click="showRuZhangDialog"
          v-hasPermi="['hmk:contrast:ruZhang']"
        >确认入账
        </el-button>
      </div>
    </el-dialog>


    <el-dialog title="确认入账" :visible.sync="ruZhangFormVisible" width="30%">
      <el-form :model="contrastFormData">
        <el-form-item label="入账账期">
          <el-date-picker v-model="contrastFormData.ruzhangTime" format="yyyyMM" value-format="yyyyMM" type="month"
                          placeholder="选择月">
          </el-date-picker>
        </el-form-item>

        <div style="margin-top: 30px;color: red">注意：同一订单可以多次入账，但是不能入相同账期</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ruZhangFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="ruZhangFormVisible2 = true">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="请输入对应账期,并确认" :visible.sync="ruZhangFormVisible2" width="15%">
      <el-form :model="contrastFormData">
        <el-input v-model="contrastFormData.ruzhangTime2"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ruZhangFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitRuZhang(contrastFormData)">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addContrast,
  delContrast,
  getContrast,
  listContrast,
  ruZhang,
  selectContrastDetailVoList,
  updateContrast
} from "@/api/hmk/contrast";
import {formatTimeTitle, formatTimeTitleExcel} from "@/utils/hjf-common"
import {getToken} from "@/utils/auth";
import {getSimpleUserList} from "@/api/system/user";

export default {
  name: "Contrast",
  data() {
    return {
      sysUserList: [],
      ruZhangFormVisible2: false,
      showRuZhangButton: false,
      ruZhangFormVisible: false,
      contrastFormData: {ruzhangTime: null, ruzhangTime2: null},
      orderContrastId: null,
      contrastData: [],
      contrastDetailList: [],
      contractDetail: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 佣金对比批次表格数据
      contrastList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        batch: null,
        status: null,
        count: null,
        ruzhangTime: null,
        time: null,
        daoruManageId: null,
        ruzhangManageId: null
      },
      // 导入参数
      upload: {
        uploadFiles: [],
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/hmk/contrast/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.sysUserList = JSON.parse(sessionStorage.getItem("sysUserList"));
    if (!this.sysUserList) {
      console.log("缓存中没有获取到userList")
      getSimpleUserList().then(response => {
        this.sysUserList = response.data;
        sessionStorage.setItem('sysUserList', JSON.stringify(this.sysUserList));
      });
    }
    this.getList();
  },
  methods: {
    submitRuZhang(form) {
      if (!form.ruzhangTime) {
        this.$message.error('入账账期必填');
        return;
      }
      if (form.ruzhangTime != form.ruzhangTime2) {
        this.$message.error('2次入账账期不匹配!');
        return;
      }
      ruZhang({'orderContrastId': this.orderContrastId, 'ruzhangTime': form.ruzhangTime}).then(res => {
        this.$message.success(res.msg);
        this.getList();
        this.showRuZhangButton = false;
        this.ruZhangFormVisible = false;
        this.ruZhangFormVisible2 = false;
        this.contractDetail = false;
        return;
      })
    },
    showRuZhangDialog() {
      this.form.ruzhangTime = null;
      this.ruZhangFormVisible = true;
    },
// 添加错误处理方法
    handleFileError(error, file, fileList) {
      // 关闭所有消息提示
      this.$message.closeAll();

      // 恢复按钮状态
      const confirmBtn = document.querySelector('.el-dialog__footer .el-button--primary');
      if (confirmBtn) {
        confirmBtn.disabled = false;
        confirmBtn.innerHTML = '确 定';
      }
      this.upload.isUploading = false;
      this.$message.error('文件上传失败: ' + (error.message || '未知错误'));
    },
    goBack() {
      this.contractDetail = false;
      this.$router.push({path: "/hmk/contrast"});
    },
    toDetail(row) {
      this.contrastFormData.ruzhangTime2 = null;
      this.contrastFormData.ruzhangTime = null;
      this.orderContrastId = row.batch;
      this.loading = true;
      this.contrastDetailList = [];
      getContrast(row.id).then(res => {
        this.contrastData = Array.isArray(res.data) ? res.data : [res.data];
        this.showRuZhangButton = (res.data.status == 1);
      })
      selectContrastDetailVoList({'orderContrastId': row.batch}).then(response => {
        this.contrastDetailList = response.rows;
        this.loading = false;
      })
      this.contractDetail = true;
    },

    importTemplate() {
      this.download('/hmk/contrast/importTemplate', {}, `contract_template_${new Date().getTime()}.xlsx`)
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      // 添加上传中提示
      this.$message({
        message: '文件上传中，请稍候...',
        type: 'info',
        duration: 0, // 不会自动关闭
        showClose: true
      });

      // 禁用确认按钮
      const confirmBtn = document.querySelector('.el-dialog__footer .el-button--primary');
      if (confirmBtn) {
        confirmBtn.disabled = true;
        confirmBtn.innerHTML = '<i class="el-icon-loading"></i> 上传中...';
      }

      // 计算并显示上传进度
      if (event.lengthComputable) {
        const percent = Math.round((event.loaded / event.total) * 100);
        console.log(`上传进度: ${percent}%`);
        // 如果需要可以在界面上显示进度条
      }
    },
    handleFileSuccess(response, file, fileList) {
      // 关闭所有消息提示
      this.$message.closeAll();

      // 恢复按钮状态
      const confirmBtn = document.querySelector('.el-dialog__footer .el-button--primary');
      if (confirmBtn) {
        confirmBtn.disabled = false;
        confirmBtn.innerHTML = '确 定';
      }

      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();

      // 显示上传成功提示
      this.$alert(
        `<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>${response.msg}</div>`,
        "导入结果",
        {
          dangerouslyUseHTMLString: true,
          callback: () => {
            this.getList();
          }
        }
      );
    },
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "分佣对比导入";
      this.upload.open = true;
    },
    formatTimeTitle,
    /** 查询佣金对比批次列表 */
    getList() {
      this.loading = true;
      listContrast(this.queryParams).then(response => {
        this.contrastList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        batch: null,
        status: null,
        count: null,
        ruzhangTime: null,
        time: null,
        daoruManageId: null,
        ruzhangManageId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加佣金对比批次";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContrast(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改佣金对比批次";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContrast(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContrast(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除佣金对比批次编号为"' + row.id + '"的数据项？').then(function () {
        return delContrast(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
      return;
    },
    /** 导出按钮操作 */
    handleExport() {

      this.download('hmk/contrast/export', {'orderContrastId': this.orderContrastId}, `佣金对比_${formatTimeTitleExcel(new Date())}.xlsx`)
    }
  }
};
</script>
